<template>
	<view>
		<uni-file-picker v-model="fileList" :auto-upload="false" :title="title"   file-mediatype="image" mode="grid"
		   :readonly="readonly"   @select="handleSelect" @delete="handleDelete"   :limit="limit"/>
	</view>
</template>

<script>
	import {
		baseUrl
	} from "@/utils/api.js"
	export default {
		props:{
			file:'',
			title:'',
			limit:{
				type:Number,
				default:9
			},
			readonly:{
				type:Boolean,
				default:false
			}
		},
		model:{
			prop:'file',
			event:'update:file'
		},
		data() {
			return {
				fileList:[]
			}
		},
		created() {
			if(this.file){
				this.fileList=this.file.split(',').map(r=>{
					return {url:r}
				})
			}
		},
		
		methods: {
			// 获取上传状态
			handleSelect(e) {
				let that=this
				let arr=e.tempFiles
				// console.log(arr);
				// console.log(this.fileList);
				let resArr= arr.map(r=>{
					return new Promise((resolve,rej)=>{
						uni.uploadFile({
							url: baseUrl + '/sysbase/sys/common/upload',
							filePath: r.url,
							name: 'file',
							formData: {
								folder: 'image',
							},
							header: {
								'X-Access-Token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MDc0MTg2NzgsInVzZXJuYW1lIjoiYWRtaW5veWMifQ.WD38O1vbi6mqi8S1bI3bvEmtrgllHy69Ci_lhBVK2Xw'
							},
							success(res) {
								let r = JSON.parse(res.data)
								that.fileList=[...that.fileList, {url:r.result.relPath}]
								that.$emit('update:file',that.fileList.map(r=>r.url).join(','))
								that.$emit('change')
							},
						});
					})
				})
				// Promise.all(resArr).then((res)=>{
				// 	console.log(res);
				// 	this.$emit('update:file',res)
				// })
				
			},
			
			handleDelete(err) { // 删除图片
				// console.log(err);
				// return
			    const num = this.fileList.findIndex(v => v.url === err.tempFilePath);
			    this.fileList.splice(num, 1);
				this.$emit('update:file',this.fileList.map(r=>r.url).join(','))
				this.$emit('change')
			},

		}
	}
</script>

<style lang="less" scoped>

</style>